package com.star.bookstore.product.service.impl;

import com.star.bookstore.product.entity.AttrEntity;
import com.star.bookstore.product.service.AttrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.star.bookstore.common.utils.PageUtils;
import com.star.bookstore.common.utils.Query;

import com.star.bookstore.product.dao.CategoryDao;
import com.star.bookstore.product.entity.CategoryEntity;
import com.star.bookstore.product.service.CategoryService;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {

        //删除关联的属性对象
        for (int i = 0; i < asList.size(); i++) {
            //只有三级分类有对应属性对象
            if (this.getById(asList.get(i)).getBookLevel() == 3) {
                //由分类id找到对应属性对象
                AttrEntity attrEntity = attrService.getByCategoryId(asList.get(i));
                attrService.removeById(attrEntity.getAttrId());
            }
        }

        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getAttrCategoryPath(AttrEntity attr) {
        List<Long> groupIdList = new ArrayList<>();
        CategoryEntity categoryEntity = this.getById(attr.getCategoryId());
        groupIdList.add(categoryEntity.getBookId());

        while (categoryEntity.getParentId() != 0) {
            groupIdList.add(categoryEntity.getParentId());
            categoryEntity = this.getById(categoryEntity.getParentId());
        }
        log.info(groupIdList.toString());
        Long[] groupIds = {groupIdList.get(2), groupIdList.get(1)};
        return groupIds;
    }

    @Override
    public void updateByIdWithAttr(CategoryEntity category) {


        List<CategoryEntity> categoryEntities = this.list();
        categoryEntities.forEach(item -> {
            AttrEntity attrEntity = null;
            //如果是二级目录,则更新categoryName字段
            if (category.getBookLevel() == 2 && item.getParentId().equals(category.getBookId())) {
                attrEntity = attrService.getByCategoryId(item.getBookId());
                attrEntity.setCategoryName(category.getName());
                attrService.updateById(attrEntity);
            }
            //如果是三级目录，则直接更新bookName字段
            if (category.getBookLevel() == 3 && item.getBookId().equals(category.getBookId())) {
                attrEntity = attrService.getByCategoryId(item.getBookId());
                attrEntity.setBookName(category.getName());
                attrService.updateById(attrEntity);
            }

        });


        this.updateById(category);

    }


    @Override
    public List<CategoryEntity> listWithTree() {

        //1.查出所有书本分类
        List<CategoryEntity> books = categoryDao.selectList(null);
        /*books.forEach(item->{
            System.out.println(item);
        });*/

        //2.、找到所有的一级分类,并设置好其子分类集合
        List<CategoryEntity> level1Menus = books.stream().filter(categoryEntity ->
                categoryEntity.getParentId() == 0
        ).map((menu) -> {
            //menu是由books流过滤之后传过来的元素（CategoryEntity）对象，相当于迭代books集合中的元素
            menu.setChildren(getChildren(menu, books));
            return menu;
        }).collect(Collectors.toList());//将查到到的数据封装成list集合

        return level1Menus;
    }

    /**
     * @param root 为一级目录中的某一元素
     * @param all  表中所有数据
     * @return 返回子目录集合
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //遍历取出表中所有数据的父分类id=等于当前目录的分类id，
            //（即在全表范围内过滤出当前传进来的root分类的所有子分类）
            return categoryEntity.getParentId() == root.getBookId();
        }).map(categoryEntity -> {
            //此时category已经查到了父分类，再以其为父分类查找其子分类
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
            //根据star字段进行排序，再封装成list集合
        }).sorted(Comparator.comparingInt(menu -> (menu.getStar() == null ? 0 : menu.getStar()))).collect(Collectors.toList());


        return children;
    }

}